import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'

// 插件的方式来使用
Vue.use(Vuex)

// 创建一个 store 对象并暴露出去
const store = new Vuex.Store({
  state: {
    cartList: uni.getStorageSync('cart') || []
  },
  mutations: {
    updateCartList(state, cartList) {
      state.cartList = cartList
      // 往本地存储一下
      uni.setStorageSync('cart', cartList)
    }
  },
  getters: {
    // 获取所有已勾选的商品
    checkedCart(state) {
      return state.cartList.filter(item => item.goods_checked)
    },
    checkedTotal(_, getters) {
      return getters.checkedCart.reduce((sum, item) => sum += item.goods_number, 0)
    },
    checkedPrice(_, getters) {
      return getters.checkedCart.reduce((sum, item) => sum += item.goods_number * item.goods_price, 0)
    }
  },
  modules: {
    user
  }
})

export default store
